using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using Mono;
using RssReader.Data;
using RssReader.Data.DatabaseTableAdapters;
using System.Data;

namespace RssReader
{
	[MonoTouch.Foundation.Register("SiteTableViewController")]
	public partial class SiteTableViewController : UITableViewController
	{
		static NSString CellID = new NSString ("CellID");
		Database.SitesDataTable AvailableSites;

		// Constructor invoked from the NIB loader
		public SiteTableViewController (IntPtr p) : base(p)
		{
			Title = "Sites";
		}

		public SiteTableViewController () : base()
		{
			Title = "Sites";
		}

		// The data source for our TableView
		class DataSource : UITableViewDataSource
		{
			SiteTableViewController tvc;

			public DataSource (SiteTableViewController tableViewController)
			{
				this.tvc = tableViewController;
			}

			public override int RowsInSection (UITableView tableView, int section)
			{
				return tvc.AvailableSites.Count;
			}

			public override void CommitEditingStyle (UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath)
			{
				if (editingStyle == UITableViewCellEditingStyle.Insert) {
					((UITextField)editorCell.ContentView.Subviews[0]).ResignFirstResponder ();
					string url = ((UITextField)editorCell.ContentView.Subviews[0]).Text;
					if (!string.IsNullOrEmpty (url)) {
						tvc.adapter.Insert (url, url, "");
						tvc.adapter.Fill (tvc.AvailableSites);
						tvc.AvailableSites.AddSitesRow ("", "", "");
						tableView.InsertRows (new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Fade);
						((UITextField)editorCell.ContentView.Subviews[0]).Text = "";
					}
				} else if (editingStyle == UITableViewCellEditingStyle.Delete) {
					SitesTableAdapter adapter = new SitesTableAdapter ();
					adapter.Delete (tvc.AvailableSites[indexPath.Row].SiteID);
					tvc.AvailableSites.Rows.RemoveAt (indexPath.Row);
					tableView.DeleteRows (new[] { indexPath }, UITableViewRowAnimation.Left);
				}
			}
			public override bool CanEditRow (UITableView tableView, NSIndexPath indexPath)
			{
				return true;
			}
			UITableViewCell editorCell;

			public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
			{
				Database.SitesRow site = tvc.AvailableSites[indexPath.Row];
				
				var cell = tableView.DequeueReusableCell (CellID);
				
				if (cell == null) {
					cell = new UITableViewCell (UITableViewCellStyle.Default, CellID);
					cell.Accessory = UITableViewCellAccessory.DisclosureIndicator;
				}
				
				
				if ((site.SiteTitle == "" && site.SiteURL == "") || (indexPath.Row >= tvc.AvailableSites.Count ())) {
					if (editorCell == null) {
						editorCell = ((UITableViewCell)new EditingTableCell ().View);
						editorCell.Draw (cell.Bounds);
						editorCell.Center = cell.Center;
						return editorCell;
					} else {
						editorCell.Center = cell.Center;
						editorCell.Draw (cell.Bounds);
						
						return editorCell;
					}
				}
				
				// Customize the cell here...
				cell.TextLabel.Text = site.SiteTitle;
				
				return cell;
			}
		}

		// This class receives notifications that happen on the UITableView
		class TableDelegate : UITableViewDelegate
		{
			SiteTableViewController tvc;

			public TableDelegate (SiteTableViewController tableViewController)
			{
				this.tvc = tableViewController;
			}
			UITextField editor;
			public override MonoTouch.UIKit.UITableViewCellEditingStyle EditingStyleForRow (UITableView tableView, NSIndexPath indexPath)
			{
				if (tvc.AvailableSites[indexPath.Row].SiteTitle == "") {
					if (tableView.CellAt (indexPath) != null) {
						if (editor == null)
							editor = ((UITextField)tableView.CellAt (indexPath).ContentView.Subviews[0]);
						editor.Enabled = true;
						editor.Selected = true;
						editor.EnablesReturnKeyAutomatically = true;
						editor.ReturnKeyType = UIReturnKeyType.Default;
						editor.ExclusiveTouch = true;
						editor.Placeholder = "";
					}
					return UITableViewCellEditingStyle.Insert;
				} else
					return UITableViewCellEditingStyle.Delete;
			}
			FeedTableViewController feedsViewController;

			public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
			{
				Database.SitesRow site = tvc.AvailableSites[indexPath.Row];
				if (site.SiteURL == "")
					return;
				feedsViewController = new FeedTableViewController ();
				feedsViewController.CurrentSite = site;
				tvc.NavigationController.PushViewController (feedsViewController, true);
			}
		}
		SitesTableAdapter adapter = new SitesTableAdapter ();

		public override void ViewDidLoad ()
		{
			NavigationItem.RightBarButtonItem = EditButtonItem;
			base.ViewDidLoad ();
			DataBind ();
			TableView.Delegate = new TableDelegate (this);
			TableView.DataSource = new DataSource (this);
		}




		public void DataBind ()
		{
			if (AvailableSites == null) {
				AvailableSites = new Database.SitesDataTable ();
				adapter.Fill (this.AvailableSites);
				AvailableSites.SitesRowChanging += HandleAvailableSitesSitesRowChanging;
				AvailableSites.SitesRowChanged += HandleAvailableSitesSitesRowChanged;
				AvailableSites.SitesRowDeleted += HandleAvailableSitesSitesRowDeleted;
				AvailableSites.SitesRowDeleting += HandleAvailableSitesSitesRowDeleting;
				AvailableSites.AddSitesRow ("", "", "");
				TableView.InsertRows (new NSIndexPath[] { NSIndexPath.FromRowSection (AvailableSites.Count () - 1, 0) }, UITableViewRowAnimation.Left);
			}
		}

		void HandleAvailableSitesSitesRowDeleting (object sender, Database.SitesRowChangeEvent e)
		{
			
		}

		void HandleAvailableSitesSitesRowDeleted (object sender, Database.SitesRowChangeEvent e)
		{
			
		}

		void HandleAvailableSitesSitesRowChanged (object sender, Database.SitesRowChangeEvent e)
		{
			
		}

		void HandleAvailableSitesSitesRowChanging (object sender, Database.SitesRowChangeEvent e)
		{
			
			
			
		}
	}
}
